import 'package:flutter_architecture/src/features/cart/application/cart_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../domain/cart.dart';

class ShoppingCartItemController extends StateNotifier<AsyncValue<void>> {
  final CartService cartService;

  ShoppingCartItemController({required this.cartService})
      : super(const AsyncData(null));

  Future<void> updateQuantity(Item item, int quantity) async {
    state = const AsyncLoading();
    final updated = Item(productId: item.productId, quantity: quantity);
    state =
        await AsyncValue.guard(() => cartService.updateItemIfExists(updated));
  }

  Future<void> deleteItem(Item item) async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(
        () => cartService.removeItemById(item.productId));
  }
}

final shoppingCartItemControllerProvider =
    StateNotifierProvider<ShoppingCartItemController, AsyncValue<void>>((ref) {
  return ShoppingCartItemController(
      cartService: ref.watch(cartServiceProvider));
});
